<?php

use think\facade\Db;
class Common
{
    /**
     * 根据分类id获取商品
     * @param $cate_id
     * @return array
     */
    public static function getCategoryGoods($cate_id,$state_home=0,$page=1,$size=16){
       $cateRelaModel = new \app\api\model\ShopGoodsCateRela();
       $can_show = 1;
       $goodsList = [];
        $startPn = ($page-1)*$size;
       $goodsList = $cateRelaModel->alias("categ")->LeftJoin("shop_goods sg","categ.goods_id = sg.id")
           ->field("sg.name,sg.cover,sg.smail_cover as img,sg.price_selling,sg.id as goods_id,sg.state_hot,sg.stock_virtual+sg.stock_sales as slogan,sg.remark,sg.price_market")
           ->where(array(
               "categ.cate_id" => $cate_id,
               "sg.status"=>1
           ))->order(array(
               "categ.sort"   => 'asc'
           ))->group("categ.goods_id")->limit($startPn,$size)->select();
            if (empty($goodsList)) {
                   $can_show = 0;
                   $goodsList = [];
               } else {
                   foreach ($goodsList as &$gv) {
                       $gv['price_market'] = sprintf("%.2f", $gv['price_market'] / 100);
                       $rate = 1;
                        $can_show_newActiviy = sysconf('base.can_show_newActiviy');
                        if($can_show_newActiviy == 1){
                            $rate = sysconf("base.newopenActivity_rate");
                            $gv['price'] = sprintf("%.2f",$gv['price_selling'] * $rate/100);
                            $gv['price_selling'] = sprintf("%.2f",$gv['price_selling'] * $rate/100);
                        }
                   }
               }
               return array(
                   'can_show'   => $can_show,
                   'goodsList'  => $goodsList
               );
    }

    /**
     * 根据品牌id获取商品
     * @param $cate_id
     * @return array
     */
    public static function getBrandGoods($brand_id,$page=1,$size=10,$order=[]){
       $total = 0;
       $total = Db::name("shop_goods_brand_rela")->alias("GR")->leftJoin("shop_goods SG","GR.goods_id = SG.id")->where(array(
           'GR.brand_id'   =>$brand_id,
           'SG.status'      =>1
       ))->count("GR.id");
       $goodsList  = Db::name("shop_goods_brand_rela")->alias("GR")
           ->leftJoin("shop_goods SG","GR.goods_id = SG.id")
           ->where(array(
           'GR.brand_id'   =>$brand_id,
           'SG.status'      =>1
       ))->field("SG.name,SG.cover as img,SG.price_selling,SG.id as goods_id,SG.state_hot,SG.stock_sales,SG.stock_virtual,SG.stock_sales+SG.stock_virtual as slogan,SG.remark,SG.price_market")->order(array(
           'GR.sort'      => 'asc',
           'SG.create_at' => 'desc'
           ))->limit(($page-1)*$size,$size)->select();
       if(empty($goodsList)){
           $goodsList = [];
           $total = 0;
       }else{
           $goodsList = $goodsList->toArray();
           $rate = 1;
           $can_show_newActiviy = sysconf('base.can_show_newActiviy');
           foreach ($goodsList as &$pv){
               $pv['price_market'] = sprintf("%.2f",$pv['price_market']/100);
               if($can_show_newActiviy == 1){
                   $rate = sysconf("base.newopenActivity_rate");
                   $pv['price'] = sprintf("%.2f",$pv['price_selling'] * $rate/100);
                   $pv['price_selling'] = sprintf("%.2f",$pv['price_selling'] * $rate/100);
               }else{
                   $pv['price'] = sprintf("%.2f",$pv['price_selling']/100);
                   $pv['price_selling'] = sprintf("%.2f",$pv['price_selling']/100);
               }
           }
       }

       return [$total,$goodsList];
    }
    /**
     * 写log
     * @return void
     */
    public static function addlog($action = '行为', $content = "内容描述",$node = '*',$ip = '127.0.0.1'){
        $logModel = new \app\api\model\SystemOplog();
        return $logModel->addData(array(
            'node'     =>  $node,
            'geoip'    =>  $ip,
            'action'    => $action,
            'content'   => $content,
            'username'  => 'admin',
            'create_at' => \Tools::getDateTimeByTime()
        ));
    }
    /**
     * 随机生成sku
     */
    public static function createSku($length = 14, $prefix = 'S'){
        $code = time();
        $len = strlen($code);
        if($len > $length){
            return $prefix.mb_substr($code,$len-$length-1,$length);
        }else{
            $l = $length - $len;
            for($i=0;$i<$l;$i++){
                $code.=rand(0,9);
            }
            return $prefix.$code;
        }
    }
        /**
     * 唯一日期编码
     * @param integer $size 编码长度
     * @param string $prefix 编码前缀
     * @return string
     */
    public static function uniqidDate(int $size = 16, string $prefix = ''): string
    {
        if ($size < 14) $size = 14;
        $code = $prefix . date('Ymd') . (date('H') + date('i')) . date('s');
        while (strlen($code) < $size) $code .= rand(0, 9);
        return $code;
    }

    /**
     * 归还商品库存
     * @param $code
     * @return void
     */
    public static function rebackStock($orderDetail,$opera=[],$type=1){
        //type =  1  未付款取消  不减销售   2  售后退货
        $goodsModel = new \app\api\model\ShopGoods();
        $goodsDetailModel = new \app\api\model\ShopGoodsItem();
        $allnum = 0;
        $productId = 0;
        $code = '';
        if(empty($orderDetail) === FALSE){
            foreach($orderDetail as &$dv){
                $opera[] = $goodsDetailModel->decNum(array(
                    'goods_sku' => $dv['goods_sku']
                ),'freeze_stock',$dv['stock_sales']);
                if($type == 2) {
                    $opera[] = $goodsDetailModel->decNum(array(
                        'goods_sku' => $dv['goods_sku']
                    ), 'stock_sales', $dv['stock_sales']);
                }
                $opera[] = $goodsDetailModel->incNum(array(
                   'goods_sku' => $dv['goods_sku']
                ),'stock_total',$dv['stock_sales']);
                $allnum += $dv['stock_sales'];
                if ($dv['product_id'] > 0) $productId = $dv['product_id'];
                $code = $dv['goods_code'];
                if($productId > 0 && $allnum > 0){
                    if($type == 1) {
                        $opera[] = $goodsModel->decNum(array(
                            'code' => $code
                        ), 'freeze_stock', $allnum);
                    }
                    $opera[] = $goodsModel->incNum(array(
                        'code' => $code
                    ),'stock_total',$allnum);
//                    if($type == 2) {
//                        $opera[] = $goodsModel->decNum(array(
//                            'code' => $code
//                        ), 'stock_sales', $allnum);
//                    }
                }
            }
        }

        return $opera;
    }

    /**
     * 保存历史检索记录
     * @param $search
     * @param $uid
     * @return void
     */
    static function saveSearch($keyword,$user_id){

        $res = \app\api\model\ShopSearchRecord::where(array(
                'user_id'=>$user_id,
                'keyword'=>$keyword,
                'del' => 0
        ))->findOrEmpty();
        if(!$res->isEmpty()){
            \app\api\model\ShopSearchRecord::where(array(
                'id'=>$res['id']
            ))->update(array(
                'count' => $res['count'] +1,
                'update_time'=>time()
            ));
        }else{
            \app\api\model\ShopSearchRecord::create(array(
                'user_id'=>$user_id,
                'keyword'=>$keyword,
                'count' => 1,
                'update_time' => time(),
                'del' => 0
            ))->save();
        }
        return true;
    }
    static function getLevel($is_first=1,$amount){
        $f_min_amount = sysconf('f_min_amount');
        $s_min_amount = sysconf('s_min_amount');
        $t_min_amount = sysconf('t_min_amount');
        $f_max_amount = sysconf('f_max_amount');
        $s_max_amount = sysconf('s_max_amount');
        $t_max_amount = sysconf('t_max_amount');

        $f_pre_rate = sysconf('f_pre_rate');
        $f_pre_pre_rate = sysconf('f_pre_pre_rate');
        $s_pre_rate = sysconf('s_pre_rate');
        $s_pre_pre_rate = sysconf('s_pre_pre_rate');
        $t_pre_rate = sysconf('t_pre_rate');
        $t_pre_pre_rate = sysconf('t_pre_pre_rate');

        if($amount < $f_max_amount){
            //第一档
            if($is_first == 1){
                $res_amount = sprintf("%.2f",$amount * $f_pre_rate/100);
            }else{
                $res_amount = sprintf("%.2f",$amount * $f_pre_pre_rate/100);
            }
        }else if($amount >= $s_min_amount && $amount < $s_max_amount){
            //第二档
            if($is_first == 1){
                $res_amount = sprintf("%.2f",$amount * $s_pre_rate/100);
            }else{
                $res_amount = sprintf("%.2f",$amount * $s_pre_pre_rate/100);
            }
        }else if($amount >= $t_min_amount){
            //第三档
            if($is_first == 1){
                $res_amount = sprintf("%.2f",$amount * $t_pre_rate/100);
            }else{
                $res_amount = sprintf("%.2f",$amount * $t_pre_pre_rate/100);
            }
        }
        return intval($res_amount);

    }

    /**
     * @param $data
     * @param $type 0 商品二维码  1  小程序首页二维码
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static function createQrcode($data,$type = 0,$name=''){
        //生成二维码
        $appid = sysconf('wx_appid');
        $secret = sysconf('wx_secret');
        $object = new \Wxchat($appid,$secret);
        $accessToken = $object->getaccesstoken();
        if($type == 1) {
            //公众号或者视频号渠道码
            $path = 'pages/index/index?channel_code=' . $data['channel_code'] . '&channel=' . $data['channel'];
            $img = $data['channel_code'] . '.png';
            $file_path = 'upload/wechat/' . $img;
            if(!is_dir('upload/wechat/')){
                mkdir('upload/wechat/',0755,true);
            }
        }else{
            $userModel = new \app\api\model\DataUser();
            $userinfo = $userModel->getOne(
                array(
                    'id' => $data['uuid'] ?? 0
                ), 'distribution_code');
            if (empty($userinfo)) {
                $distribution_code = 'test';
            }else {
                $distribution_code = $userinfo['distribution_code']??'test';
            }
            if(empty($name)) {
                $path = 'pagesB/goods/goods?share_user_code=' . $distribution_code . '&id=' . $data['goods_id'] ?? 0;
                $img = $distribution_code . '.png';
            }else{
                $path = 'pagesB/goods/goods?id=' . $data['goods_id'] ?? 0;
                $img = $data['goods_id'].'.png';
            }
            $file_path = 'upload/share/' . $img;
            if(!is_dir('upload/share/')){
                mkdir('upload/share/',0755,true);
            }
        }
        $res = $object->createqrcodea($accessToken, $path);

        file_put_contents($file_path, $res['data']);
        //上传oss
            $bucket = sysconf('storage.alioss_bucket');
            $OSS_URL = sysconf('storage.alioss_http_domain');
            $OSS_ACCESS_ID = sysconf('storage.alioss_access_key');
            $OSS_ACCESS_KEY = sysconf('storage.alioss_secret_key');
            $server = new \OSS\OssClient($OSS_ACCESS_ID, $OSS_ACCESS_KEY, $OSS_URL, true);
            self::upfile2oss($server, 'qrcode/' . $img, $bucket, $_SERVER['DOCUMENT_ROOT'] . '/' . $file_path);
            $f_name = 'https://' . $OSS_URL . '/qrcode/' . $img;//已经生成的原始二维码图片文件
            //保存图片,销毁图形，释放内存
            if (!file_exists($_SERVER['DOCUMENT_ROOT'] . '/' . $file_path)) {
                unlink($_SERVER['DOCUMENT_ROOT'] . '/' . $file_path);
            }
            return $f_name;
    }

    /**
     * 上传文件
     * @param $server
     * @param $file_name
     * @param $bucket
     * @param $path
     * @return bool
     */
    public static function upfile2oss($server, $file_name, $bucket, $path)
    {
        $upload = $server->uploadFile($bucket, $file_name, $path);
        if ($upload['info']['http_code'] == 200) {
            return $upload;
        } else {
            return false;
        }
    }
        /**
     * 计算提成
     * @param $payment_amount
     * @return int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    static function getTicheng($payment_amount){
        if($payment_amount <= 0) return 0;
        $channel_f_pre_rate = sysconf('channel_f_pre_rate');
        $channel_s_min_amount = sysconf('channel_s_min_amount');
        $channel_s_max_amount = sysconf('channel_s_max_amount');
        $channel_s_pre_rate = sysconf('channel_s_pre_rate');
        $channel_t_min_amount = sysconf('channel_t_min_amount');
        $channel_t_pre_rate = sysconf('channel_t_pre_rate');
        if($payment_amount >= $channel_t_min_amount){
            return sprintf("%.2f",$payment_amount * $channel_t_pre_rate / 10000);
        }elseif($payment_amount >= $channel_s_min_amount && $payment_amount < $channel_s_max_amount){
            return sprintf("%.2f",$payment_amount * $channel_s_pre_rate / 10000);
        }else{
            return sprintf("%.2f",$payment_amount * $channel_f_pre_rate / 10000);
        }
    }
    public static function downloadQrcode($info){
        $path = $_SERVER['DOCUMENT_ROOT'] . '/runtime/temp';
        $suffix = substr(strrchr($info['qrcode_path'], '.'), 1);//文件后缀
        $filename = substr(strrchr($info['qrcode_path'], '/'), 1);//文件名称
        $respath = \Tools::downfile($info['qrcode_path'],$path);//下载远程文件到本地路径
        //执行浏览器下载
        \Tools::download_file($respath, $filename);
        if (file_exists($respath)) {
            unlink($respath);
        }
    }
}
